
from fastapi import APIRouter, Depends
from schemas.common import RETURN, ListRequest
from sqlmodel import Session
from sqlmodel.ext.asyncio.session import AsyncSession
from fastapi_cache.decorator import cache
import os
from sqlalchemy.future import select
from sqlalchemy.sql.expression import distinct

from addons.Oss import Aly
import models.admin.system.Admin as AdminModel
import models.admin.system.Attachment as AttachmentModel

from server.Base import BaseServer
from database.mysql import get_async_session
from core.Depend import  has_permission
from core.Config import settings

router = APIRouter(prefix="/General", tags=["常规配置"])

# 查看附件后缀
@router.get("/AttachmentType/list",summary="附件类型列表")
async def AttachmentType_list(user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachmenttype_list"))):
    return RETURN.success("查询成功",settings.ALLOWED_EXTENSIONS)


# 查看所有附件
@router.post("/Attachment/list",summary="附件列表")
async def Attachment_list(request:ListRequest, user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachment_list"))):
    data = await BaseServer(AttachmentModel.Attachment).list(request)
    # 遍历数据，根据storage字段，拼接url
    for item in data.list:
        if item["storage"] == "local":
            item["url"] = settings.STATIC_PREFIX + item["url"]
        if item["storage"] == "oss":
            item["url"] = Aly.get_url(item["url"])
    return RETURN.success("查询成功",data)

# 删除附件
@router.delete("/Attachment/delete",summary="附件删除")
async def Attachment_delete(id: int, user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachment_del"))):
    # 同步删除文件
    data = await BaseServer(AttachmentModel.Attachment).get(id)
    if data:
        if data["storage"] == "local":
            try:
                path = os.path.join(settings.STATIC_DIR, data["url"].lstrip('/\\'))
                os.remove(path)
            except:
                pass
        if data["storage"] == "oss":
            await Aly.delete_file(data["url"])
    else:
        return RETURN.fail("附件不存在")

    await BaseServer(AttachmentModel.Attachment).delete(id)
    return RETURN.success("删除成功")

# 批量删除
@router.delete("/Attachment/batchDelete",summary="附件批量删除")
async def Attachment_batchDelete(ids: list[int], user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachment_batch_del"))):
    for id in ids:
        data = await BaseServer(AttachmentModel.Attachment).get(id)
        if data:
            if data["storage"] == "local":
                try:
                    path = os.path.join(settings.STATIC_DIR, data["url"].lstrip('/\\'))
                    os.remove(path)
                except:
                    pass
            if data["storage"] == "oss":
                await Aly.delete_file(data["url"])
        else:
            return RETURN.fail("附件不存在")
    await BaseServer(AttachmentModel.Attachment).deleteAll(ids)
    return RETURN.success("删除成功")


# 获取附件 category 去重后的列表
@router.get("/Attachment/category",summary="附件分类")
@cache(expire=60)
async def Attachment_category(user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachment_category")), session: AsyncSession = Depends(get_async_session)):
    state = select(distinct(AttachmentModel.Attachment.category)).where(AttachmentModel.Attachment.category != "")
    result = await session.exec(state)
    datas = result.fetchall()
    # 将查询结果转换为列表
    data = [row[0] for row in datas]
    return RETURN.success("查询成功",data)

# 根据id修改附件类型
@router.post("/Attachment/updateCategory",summary="修改附件分类")
async def Attachment_updateCategory(id: int, category: str, user: AdminModel.redis_admin = Depends(has_permission("system_admin_attachment_update_category")), session: AsyncSession = Depends(get_async_session)):
    # attachment = session.query(AttachmentModel.Attachment).filter(AttachmentModel.Attachment.id == id).first()
    state = select(AttachmentModel.Attachment).where(AttachmentModel.Attachment.id == id)
    result = await session.exec(state)
    attachment = result.scalars().first()
    if attachment is None:
        return RETURN.fail("附件不存在")
    attachment.category = category
    session.add(attachment)
    await session.commit()
    return RETURN.success("修改成功")